﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing.Imaging;
using System.Linq.Expressions;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace IML.MVC.Models
{
    public class ErrorImageResult : ActionResult
    {
        #region Properties
        private Bitmap _b { get; set; } 
        #endregion

        #region Constructors
        public ErrorImageResult(string errorText)
        {
            _setup(errorText, 640, 50);
        }

        public ErrorImageResult(string errorText, int width, int height)
        {
            _setup(errorText, width, height);
        } 
        #endregion

        #region Private Methods
        private void _setup(string errorText, int width, int height)
        {
            _b = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(_b);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Rectangle rect = new Rectangle(0, 0, width, height);
            g.FillRectangle(new SolidBrush(Color.White), rect);
            // Set up the text font.
            SizeF size;
            float fontSize = height + 4;
            Font font;
            // Adjust the font size until the text fits within the image.
            do
            {
                fontSize--;
                font = new Font("Century Schoobook", fontSize, FontStyle.Bold);
                size = g.MeasureString(errorText, font);
            } while (size.Width > width);

            // Set up the text format.
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            // Create a path using the text and warp it randomly.
            GraphicsPath path = new GraphicsPath();
            path.AddString(errorText, font.FontFamily, (int)font.Style, font.Size, rect, format);
            g.FillPath(new SolidBrush(Color.Black), path);
            // Clean up.
            font.Dispose();
            g.Dispose();
        } 
        #endregion

        #region ActionResult Required Methods
        public override void ExecuteResult(ControllerContext context)
        {
            HttpContextBase cb = context.HttpContext;
            cb.Response.Clear();
            cb.Response.ContentType = "image/bmp";
            _b.Save(cb.Response.OutputStream, ImageFormat.Bmp);
            _b.Dispose();
        } 
        #endregion
    }
}